import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { UserService } from '../user/user.service';
import { JwtValidateUserDto } from './dto/jwt-user.dto';

@Injectable()
export class JWTStrategyService extends PassportStrategy(Strategy) {
  constructor(
    readonly configService: ConfigService,
    private userService: UserService,
  ) {
    super({
      jwtFromRequest: ExtractJwt.fromHeader(
        configService.get('API_ACCESS_TOKEN_HEADER'),
      ),
      secretOrKey: configService.get('API_ACCESS_TOKEN_SECRET'),
    });
  }

  async validate(user: JwtValidateUserDto) {
    const u = await this.userService.findUserEmail(user.email);
    if (u) {
      const { password, ...res } = u;
      return res;
    }

    return null;
  }
}
